import store from '@/store';

export const useTabViewStore = defineStore('tabView', () => {
  // state
  const state = reactive<{
    cacheViews: any;
    fixedViews: any;
    tabViews: any;
  }>({
    cacheViews: {}, // 开启缓存的页面
    fixedViews: {}, // 固定不能被关闭的tab页面
    tabViews: {}, // tab页面列表
  });

  // actions
  const addTabView = (view: any) => {
    if (!state.fixedViews[view.path]) {
      state.tabViews[view.path] = view;
    }
  };

  const closeTabView = (index: number) => {
    Object.keys(state.tabViews).forEach((key, indexT) => {
      if (index - getFixedViews.value.length === indexT) {
        delete state.tabViews[key];
      }
    });
  };

  const getTabViews = computed(() => {
    return Object.keys(state.fixedViews)
      .map((key) => state.fixedViews[key])
      .concat(
        Object.keys(state.tabViews)
          .map((key) => state.tabViews[key])
          .filter((item) => item),
      );
  });
  const addCacheView = (view: any) => {
    state.cacheViews[view.path] = view;
  };

  const getCacheViews = computed(() => {
    return Object.keys(state.cacheViews).map((key) => state.cacheViews[key].name);
  });

  const addFixedView = (view: any) => {
    state.fixedViews[view.path] = view;
  };

  const getFixedViews = computed(() => {
    return Object.keys(state.fixedViews).map((key) => state.fixedViews[key]);
  });

  return {
    ...toRefs(state),
    addTabView,
    closeTabView,
    getTabViews,
    addCacheView,
    getCacheViews,
    addFixedView,
    getFixedViews,
  };
});

// 在组件外部用pinia就调用这个方法
export function useTabViewStoreWithOut() {
  return useTabViewStore(store);
}
